﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

using Microsoft.ApplicationBlocks.Data;

using DotNetNuke.Common.Utilities;
using DotNetNuke.Framework.Providers;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Providers.BlogSiteMapProvider.Entities;
namespace DotNetNuke.Providers.BlogSiteMapProvider.Data

{
    internal class SqlDataProvider : DataProvider 
    {
        private const string ModuleQualifier = "bsp_";
        private const string OwnerQualifier = "ifty_";

        #region Private Members
        private const string ProviderType = "data";
        private ProviderConfiguration _providerConfiguration = ProviderConfiguration.GetProviderConfiguration(ProviderType);
        private string _connectionString;
        private string _providerPath;
        private string _objectQualifier;
        private string _databaseOwner;
        #endregion
        #region Constructor
        /// <summary>
        /// Constructs new SqlDataProvider instance
        /// </summary>
        internal SqlDataProvider()
        {
            //Read the configuration specific information for this provider
            Provider objProvider = (Provider)_providerConfiguration.Providers[_providerConfiguration.DefaultProvider];

            //Read the attributes for this provider
            //Get Connection string from web.config
            _connectionString = Config.GetConnectionString();

            if (_connectionString.Length == 0)
            {
                // Use connection string specified in provider
                _connectionString = objProvider.Attributes["connectionString"];
            }

            _providerPath = objProvider.Attributes["providerPath"];

            //override the standard dotNetNuke qualifier with a iFinity one if it exists
            _objectQualifier = objProvider.Attributes["objectQualifier"];
            if ((_objectQualifier != "") && (_objectQualifier.EndsWith("_") == false))
            {
                _objectQualifier += "_";
            }
            else
                if (_objectQualifier == null) _objectQualifier = "";

            _objectQualifier += OwnerQualifier;

            _databaseOwner = objProvider.Attributes["databaseOwner"];
            if ((_databaseOwner != "") && (_databaseOwner.EndsWith(".") == false))
            {
                _databaseOwner += ".";
            }
        }
        #endregion
        #region Properties

        /// <summary>
        /// Gets and sets the connection string
        /// </summary>
        public string ConnectionString
        {
            get { return _connectionString; }
        }
        /// <summary>
        /// Gets and sets the Provider path
        /// </summary>
        public string ProviderPath
        {
            get { return _providerPath; }
        }
        /// <summary>
        /// Gets and sets the Object qualifier
        /// </summary>
        public string ObjectQualifier
        {
            get { return _objectQualifier; }
        }
        /// <summary>
        /// Gets and sets the database ownere
        /// </summary>
        public string DatabaseOwner
        {
            get { return _databaseOwner; }
        }

        #endregion
        #region private members
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets the fully qualified name of the stored procedure
        /// </summary>
        /// <param name="name">The name of the stored procedure</param>
        /// <returns>The fully qualified name</returns>
        /// -----------------------------------------------------------------------------
        private string GetFullyQualifiedName(string name)
        {
            return DatabaseOwner + ObjectQualifier + ModuleQualifier + name;
        }

        private string GetSafeString(SqlDataReader rdr, string name, string defaultValue)
        {
            string result = defaultValue;
            if (Convert.IsDBNull(rdr[name]) == false)
                result = (string)rdr[name];
            return result;

        }
        private int GetSafeInt(SqlDataReader rdr, string name, int defaultValue)
        {
            int result = defaultValue;
            if (Convert.IsDBNull(rdr[name]) == false)
                result = (int)rdr[name];
            return result;
        }
        private DateTime GetSafeDateTime(SqlDataReader rdr, string name, DateTime defaultValue)
        {
            DateTime result = defaultValue;
            if (Convert.IsDBNull(rdr[name]) == false)
                result = (DateTime)rdr[name];
            return result;
        }
        private decimal GetSafeDecimal(SqlDataReader rdr, string name, decimal defaultValue)
        {
            decimal result = defaultValue;
            if (Convert.IsDBNull(rdr[name]) == false)
                result = (decimal)rdr[name];
            return result;
        }
        #endregion


        #region abstract overridden properties
        public override int GetBlogEntries(int portalId, int moduleId, out List<Entities.EntryInfo> entries, out List<Entities.BlogInfo> blogs)
        {
            int count = 0;
            entries = new List<EntryInfo>();
            blogs = new List<BlogInfo>();
            string sp = GetFullyQualifiedName("GetBlogEntries");
            SqlParameter[] parms = new SqlParameter[2];
            parms[0] = new SqlParameter("@PortalId", portalId);
            parms[1] = new SqlParameter("@moduleId", moduleId);
            //call the db
            SqlDataReader rdr = SqlHelper.ExecuteReader(_connectionString, CommandType.StoredProcedure, sp, parms);
            while (rdr.Read())
            {
                count++;
                EntryInfo entry = new EntryInfo();
                entry.EntryId = GetSafeInt(rdr, "EntryId", -1);
                entry.BlogId = GetSafeInt(rdr, "BlogId", -1);
                entry.Title = GetSafeString(rdr, "Title", "");
                entry.AddedDate = GetSafeDateTime(rdr, "AddedDate", DateTime.MinValue);
                entry.Permalink = GetSafeString(rdr, "Permalink", "");
                entry.LatestCommentDate = GetSafeDateTime(rdr, "LatestCommentDate", DateTime.MinValue);
                entries.Add(entry);
            }
            if (rdr.NextResult())
            {
                while (rdr.Read())
                {
                    BlogInfo blog = new BlogInfo();
                    blog.BlogId = GetSafeInt(rdr, "BlogId", -1);
                    blog.UserId = GetSafeInt(rdr, "UserId", -1);
                    blog.Title = GetSafeString(rdr, "Title", "");
                    blog.LastEntry = GetSafeDateTime(rdr, "LastEntry", DateTime.MinValue);
                    blog.Created = GetSafeDateTime(rdr, "Created", DateTime.MinValue);
                    blogs.Add(blog);
                    count++;
                }
            }
            rdr.Close();
            rdr.Dispose();
            return count;
            
        }
        public override int  GetBlogArchives(int portalId, int moduleId, out List<ArchiveInfo> archiveDates)
        {
            int count = 0;
            archiveDates = new List<ArchiveInfo>();
            string sp = GetFullyQualifiedName("GetBlogArchives");
            SqlParameter[] parms = new SqlParameter[2];
            parms[0] = new SqlParameter("@PortalId", portalId);
            parms[1] = new SqlParameter("@moduleId", moduleId);
            //call the db
            SqlDataReader rdr = SqlHelper.ExecuteReader(_connectionString, CommandType.StoredProcedure, sp, parms);
            while (rdr.Read())
            {
                ArchiveInfo archive = new ArchiveInfo();
                archive.BlogId = GetSafeInt(rdr, "BlogId", -1);
                archive.Year = GetSafeInt(rdr, "Year", 0);
                archive.Month = GetSafeInt(rdr, "Month", 0);
                archive.Day = GetSafeInt(rdr, "Day", 0);
                archiveDates.Add(archive);
            }
            rdr.Close();
            rdr.Dispose();
            return count;

        }

        #endregion
    }
}
